var $ = exports
var objectUtils = require("objectUtils")
var ru = require("regexpUtils")
require("arrayUtils")

var escapedProto = {isEscaped: true}
var escaped = function(str) {
	var rv = objectUtils.beget(escapedProto)
	rv.text = str
	return rv
}

$.generate = function(templateStr, separator) {
	separator = separator || "$$"
	separator = ru.escape(separator) 
	var varRegex = new RegExp(separator+"([a-z_A-Z]+)"+separator)
	var parts = []
	var t = templateStr
	var match = null
	
	while (match = varRegex.exec(t)) { (function() {
		var index = match.index
		var length = match[0].length
		var name = "" + match[1]
		var pre = escaped(t.substring(0,index))
		                      
		parts.push( function() {return pre} )
		parts.push( function(params) {
			return params[name]
		})
		t = t.substring(index + length)
	})()}
	parts.push( function() {return escaped(t)} )
	
	return function(params) {
		return parts.map( function(p) {return p(params)} )
	}
}